﻿using JetBrains.Annotations;
using System.Threading.Tasks;
using Volo.Abp;
using Volo.Abp.Domain.Services;

namespace Acme.BookStore.Bass
{
    public class BasManager : DomainService
    {
        private readonly IBasRepository _basRepository;

        public BasManager(IBasRepository basRepository)
        {
            _basRepository = basRepository;
        }

        public async Task<Bas> CreateAsync(
            [NotNull] string code,

            [CanBeNull] string name = null)
        {
            Check.NotNullOrWhiteSpace(code, nameof(code));

            var existingBas = await _basRepository.FirstOrDefaultAsync(x => x.Code == code);
            if (existingBas != null)
            {
                throw new BasAlreadyExistsException(name);
            }

            return new Bas()
            {
                Code = code,
                Name = name
            };
        }

        public async Task ChangeCodeAsync(
            [NotNull] Bas bas,
            [NotNull] string newCode)
        {
            Check.NotNull(bas, nameof(bas));
            Check.NotNullOrWhiteSpace(newCode, nameof(newCode));

            var existingBas = await _basRepository.FirstOrDefaultAsync(x => x.Code == newCode);
            if (existingBas != null && existingBas.Id != bas.Id)
            {
                throw new BasAlreadyExistsException(newCode);
            }

            bas.ChangeCode(newCode);
        }
    }
}